<template>
  <div class="mainpg">
    <div class="main_spac1">
      <div class="main_white padding10">
        <div class="mainor_form">
          <el-form
            :inline="true"
            :model="form"
            class="demo-form-inline"
            ref="userListFrom"
            label-width="80px"
            id="form"
          >
            <el-form-item label="车牌号：" prop="plate_number">
              <el-input
                v-model.trim="form.plate_number"
                placeholder="车牌号"
                clearable
                class="wid220"
              ></el-input>
            </el-form-item>
            <MainFormBtn @reset="reset" @getSearchFor="getArticleList" :loading="listLoading" :showBtn="false">
            </MainFormBtn>
          </el-form>
        </div>
        <div class="main-controls-wrap">
          <div>
            <el-button
              type="primary"
              @click="(addedFormVisible = true), (type = 0)"
              >新增车辆</el-button
            >
          </div>
        </div>
        <div class="main_table">
          <el-table
            ref="multipleTable"
            v-loading="listLoading"
            :data="list.list.data"
            element-loading-text="加载中"
            fit
            border
            highlight-current-row
            :height="borderHeight"
            :header-cell-class-name="this.$verticaline"
            :header-cell-style="tableHeightStyle"
            @header-dragend="changeTableWidth"
          >
            <el-table-column
              label="车牌号"
              prop="plate_number"
              :width="tableWidth[hash + 'plate_number']"
            />
            <el-table-column
              label="货箱长（m）"
              prop="length"
              :width="tableWidth[hash + 'length']"
            />
            <el-table-column
              label="货箱宽（m）"
              prop="width"
              :width="tableWidth[hash + 'width']"
            />
            <el-table-column
              label="货箱高（m）"
              prop="height"
              :width="tableWidth[hash + 'height']"
            />
            <el-table-column
              label="载重（t）"
              prop="load"
              :width="tableWidth[hash + 'load']"
            />
            <el-table-column
              label="描述"
              prop="remark"
              :width="tableWidth[hash + 'remark']"
            />
            <el-table-column
              label="管理操作"
              align="center"
              fixed="right"
              prop="operate"
              :width="tableWidth[hash + 'operate'] || 240"
              class-name="main_hei"
            >
              <template slot-scope="scope">
                <el-link
                  type="primary"
                  @click="
                    (addedFormVisible = true),
                      (type = 1),
                      (id = scope.row.id),
                      edit_assig(scope.$index)
                  "
                  >编辑</el-link
                >
                <el-link type="warning" @click="handleLocation(scope.row)"
                  >定位</el-link
                >
                <el-link
                  type="danger"
                  @click="(id = scope.row.id), delet(scope.$index)"
                  >删除</el-link
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="main_page boxdq">
          <div></div>
          <!-- 分页 -->
          <div class="main_page_r">
            <MainPagination
              :current-page="current.page"
              :page-sizes="[20, 30, 50, 100]"
              :page-size="limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCount"
              background
              @size-change="changeLimit"
              @current-change="changePage"
            />
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      :title="type == 1 ? '编辑车辆' : '新增车辆'"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="close(1)"
      :visible.sync="addedFormVisible"
      class="main_dialog dialog500"
    >
      <el-form
        :inline="false"
        :model="info"
        :rules="rules"
        class="demo-form-inline form-message-mg"
        ref="userListFrom"
        label-width="120px"
      >
        <el-form-item label="车牌号：" prop="plate_number">
          <el-input
            v-model.trim="info.plate_number"
            placeholder="车牌号"
            maxlength="20"
            clearable
            class="wid300"
          ></el-input>
        </el-form-item>
        <el-form-item label="货箱长（m）：" prop="length">
          <el-input
            v-model.trim="info.length"
            placeholder="货箱长（m）"
            clearable
            class="wid300"
          ></el-input>
        </el-form-item>
        <el-form-item label="货箱宽（m）：" prop="width">
          <el-input
            v-model.trim="info.width"
            placeholder="货箱宽（m）"
            clearable
            class="wid300"
          ></el-input>
        </el-form-item>
        <el-form-item label="货箱高（m）：" prop="height">
          <el-input
            v-model.trim="info.height"
            placeholder="货箱高（m）"
            clearable
            class="wid300"
          ></el-input>
        </el-form-item>
        <el-form-item label="载重（t）：" prop="load">
          <el-input
            v-model.trim="info.load"
            placeholder="载重（t）"
            clearable
            class="wid300"
          ></el-input>
        </el-form-item>
        <el-form-item label="描述：" prop="remark">
          <el-input
            v-model.trim="info.remark"
            placeholder="描述"
            clearable
            class="wid300"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="(addedFormVisible = false), close()"
          >取 消</el-button
        >
        <el-button type="primary" @click="setupmine(1)" v-repeatClick
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      title="绑定车机盒子"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="close(2)"
      :visible.sync="location_visiable"
      class="main_dialog dialog500"
    >
      <el-form
        :inline="false"
        :model="location_form"
        :rules="rules"
        class="demo-form-inline"
        ref="locationFrom"
        label-width="120px"
      >
        <el-form-item label="车牌号：" prop="plate_number">
          <el-input
            v-model.trim="location_form.plate_number"
            placeholder="车牌号"
            maxlength="20"
            disabled
            clearable
            class="wid300"
          ></el-input>
        </el-form-item>
        <el-form-item label="盒子编号：" prop="openCarId">
          <el-input
            v-model.trim="location_form.openCarId"
            placeholder="盒子编号"
            clearable
            class="wid300"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close(2)">取 消</el-button>
        <el-button type="primary" @click="setupmine(2)" v-repeatClick
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mixins } from "@/mixins/index.js";
import {
  car_index,
  car_add,
  car_edit,
  car_delete,
  car_confirmDelete,
  car_bindCar,
} from "@/api/distribution/distributionVehicle";
import rules from "@/rules/distribution/distributionVehicle";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";

export default {
  mixins: [mixins],
  components: {},
  data() {
    return {
      // 增加和编辑
      info: {
        plate_number: "",
        length: "",
        width: "",
        height: "",
        load: "",
        remark: "",
      },
      type: 0,
      id: 0,
      addedFormVisible: false,
      // 搜索
      form: {
        plate_number: "",
      },
      // 验证
      rules,
      // 分页
      current: {
        page: 1,
        per_page: 20,
      },
      limit: 20,
      totalCount: 1,
      // 列表数据
      list: {
        list: {
          data: [],
        },
      },
      listLoading: false,
      // 绑定车机盒子
      location_form: {
        id: "",
        openCarId: "",
        plate_number: "",
      },
      location_visiable: false,
    };
  },
  methods: {
    reset() {
      this.$refs['userListFrom'].resetFields()
      this.car_index();
    },
    startGetting() {
      this.startGetting();
    },
    // 关闭清空表单
    close(type) {
      switch (type) {
        case 1:
          this.info = {
            plate_number: "",
            length: "",
            width: "",
            height: "",
            load: "",
            remark: "",
          };
          this.$refs["userListFrom"].clearValidate();
          break;
        case 2:
          this.location_form = {
            plate_number: "",
            openCarId: "",
            id: "",
          };
          this.location_visiable = false;
          break;
      }
    },
    // 搜索
    getArticleList() {
      this.current.page = 1;
      this.car_index();
    },
    // 删除
    delet(index) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { id: this.id })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: this.id }
      );
      this.$confirm("是否删除车辆?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          car_delete(data).then((res) => {
            if (res.errcode == 0) {
              this.$message({
                message: "删除成功",
                type: "success",
              });
              this.list.list.data.splice(index, 1);
            } else if (res.errcode == 40030) {
              this.$confirm("是否强制删除车辆?", "提示", {
                confirmButtonText: "强制删除",
                cancelButtonText: "取消",
                type: "warning",
              })
                .then(() => {
                  car_confirmDelete(data).then((res) => {
                    if (res.errcode == 0) {
                      this.list.list.data.splice(index, 1);
                    }
                  });
                })
                .catch(() => {});
            } else {
              this.$message.error(res.errmsg);
            }
          });
        })
        .catch(() => {});
    },
    // 确认
    setupmine(type) {
      switch (type) {
        case 1:
          this.$refs["userListFrom"].validate((valid) => {
            if (valid) {
              this.type == 0 ? this.add() : this.edit();
            }
          });
          break;
        case 2:
          this.$refs["locationFrom"].validate((valid) => {
            if (valid) {
              this.car_bindCar();
            }
          });
          break;
      }
    },
    // 编辑赋值
    edit_assig(index) {
      this.info = {
        plate_number: this.list.list.data[index].plate_number,
        length: this.list.list.data[index].length,
        width: this.list.list.data[index].width,
        height: this.list.list.data[index].height,
        load: this.list.list.data[index].load,
        remark: this.list.list.data[index].remark,
      };
    },
    // 新增保存
    add() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, this.info)) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.info
      );
      car_add(data).then((res) => {
        this.addedFormVisible = false;
        if (res.errcode == 0) {
          this.$message({
            message: "新增成功",
            type: "success",
          });
          this.current.page = 1;
          this.car_index();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 编辑保存
    edit() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, this.info, { id: this.id })
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.info,
        { id: this.id }
      );

      car_edit(data).then((res) => {
        this.addedFormVisible = false;
        if (res.errcode == 0) {
          this.$message({
            message: "编辑成功",
            type: "success",
          });
          this.car_index();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 分页
    changeLimit(pageSize) {
      this.current.per_page = pageSize;
      this.car_index();
    },
    changePage(page) {
      this.current.page = page;
      this.car_index();
    },
    // 列表
    car_index() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, this.current)) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        JSON.parse(JSON.stringify(this.form)),
        this.current
      );
      car_index(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          this.list = res.data;
          this.totalCount = res.data.list.total;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    handleLocation(row) {
      this.location_form.plate_number = row.plate_number;
      this.location_form.id = row.id;
      this.location_form.openCarId = row.open_car_id;
      this.location_visiable = true;
    },
    // 绑定
    car_bindCar() {
      let data = Object.assign({}, this.location_form);
      car_bindCar(data).then((res) => {
        if (res.errcode == 0) {
          this.$message.success("绑定成功");
          this.location_visiable = false;
          this.car_index();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
  },
  created() {
    // 列表
    this.getNumerical(200);
    this.car_index();
  },
};
</script>
<style lang="scss" scoped>
.mainor_form form {
  width: calc(100% - 120px);
}
/deep/.el-form-item--small.el-form-item {
  margin-bottom: 10px;
}
</style>
